package com.jc.common.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class NetworkUtil {
	/**
	 * Logger for this class
	 */
	private static Logger		logger			= Logger.getLogger(NetworkUtil.class);
	/**
	 * what we return when we cannot determine our hostname. We use this rather than 'localhost' as if DNS is very confused, localhost can map to different machines than "self".
	 */
	public static final String	LOCALHOST		= "127.0.0.1";

	/**
	 * loopback address in IPV6
	 */
	public static final String	LOCALHOST_IPV6	= "0:0:0:0:0:0:0:1";

	/**
	 * keep this uninstantiable.
	 */
	private NetworkUtil() {}

	/**
	 * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public final static String getIpAddress(HttpServletRequest request) {
		// 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址  
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			} else {
				return ip;
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			} else {
				return ip;
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			} else {
				return ip;
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			} else {
				return ip;
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			} else {
				return ip;
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}

	public static boolean isWindowsOS() {
		return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
	}

	/**
	 * 获得主机IP
	 * @return String
	 */
	public static InetAddress getLocalInetAddress() {
		InetAddress ip = null;
		try {
			//如果是Windows操作系统
			if (isWindowsOS()) {
				ip = InetAddress.getLocalHost();
			}
			//如果是Linux操作系统
			else {
				boolean bFindIP = false;
				Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
				while (netInterfaces.hasMoreElements()) {
					if (bFindIP) {
						break;
					}
					NetworkInterface ni = netInterfaces.nextElement();
					//----------特定情况，可以考虑用ni.getName判断
					//遍历所有ip
					Enumeration<InetAddress> ips = ni.getInetAddresses();
					while (ips.hasMoreElements()) {
						ip = ips.nextElement();
						if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() //127.开头的都是lookback地址
								&& ip.getHostAddress().indexOf(":") == -1) {
							bFindIP = true;
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ip;
	}

	/**
	 * 获取本机ip地址，并自动区分Windows还是linux操作系统
	 * @return String
	 */
	public static String getLocalIP() {
		InetAddress localInetAddress = getLocalInetAddress();
		return localInetAddress == null ? null : localInetAddress.getHostAddress();
	}

	public static String getLocalHostname() {
		String hostname;
		try {
			InetAddress address = InetAddress.getLocalHost();
			hostname = address.getHostName();
			if (hostname == null || hostname.length() == 0) hostname = address.toString();
		} catch (UnknownHostException noIpAddrException) {
			if (logger.isDebugEnabled()) logger.debug("Failed to lookup local IP address", noIpAddrException);
			hostname = "127.0.0.1";
		}
		return hostname;
	}
}